#!/bin/bash

Install_Openresty() {
	cd $oneinstack_dir/src
	src_url=http://mirrors.linuxeye.com/oneinstack/src/pcre-$pcre_version.tar.gz && Download_src
	src_url=https://openresty.org/download/openresty-$openresty_version.tar.gz && Download_src

	tar xzf pcre-$pcre_version.tar.gz
	cd pcre-$pcre_version
	./configure
	make && make install
	cd ..

	id -u $run_user >/dev/null 2>&1
	[ $? -ne 0 ] && useradd -M -s /sbin/nologin $run_user

	tar xzf openresty-$openresty_version.tar.gz
	cd openresty-$openresty_version

	[ ! -d "$openresty_install_dir" ] && mkdir -p $openresty_install_dir
	./configure --prefix=$openresty_install_dir --user=$run_user --group=$run_user --with-http_stub_status_module --with-luajit --without-http_redis2_module --with-http_iconv_module --with-http_gzip_static_module --with-pcre=$oneinstack_dir/src/pcre-$pcre_version --with-pcre-jit
	make && make install

	if [ -e "$openresty_install_dir/nginx/conf/nginx.conf" ];then
	    cd ..
	    rm -rf openresty-$openresty_version
	    echo "${CSUCCESS}Openresty install successfully! ${CEND}"
	else
	    rm -rf $openresty_install_dir
	    echo "${CFAILURE}Openresty install failed, Please Contact the author! ${CEND}" 
	    kill -9 $$
	fi

	[ "$OS" == 'CentOS' ] && { [ -f /etc/init.d/nginx] && mv /etc/init.d/nginx{,_bak}; /bin/cp ../init.d/Openresty-init-CentOS /etc/init.d/nginx; chkconfig --add nginx; chkconfig nginx on; }
	cd ..

	sed -i "s@/usr/local/openresty/nginx@$openresty_install_dir/nginx@g" /etc/init.d/nginx

	mv $openresty_install_dir/nginx/conf/nginx.conf{,_bk}
	if [[ $Apache_version =~ ^[1-2]$ ]];then
	    /bin/cp config/nginx_apache.conf $openresty_install_dir/nginx/conf/nginx.conf
	elif [[ $Tomcat_version =~ ^[1-2]$ ]] && [ ! -e "$php_install_dir/bin/php" ];then
	    /bin/cp config/nginx_tomcat.conf $openresty_install_dir/nginx/conf/nginx.conf
	else
	    /bin/cp config/nginx.conf $openresty_install_dir/nginx/conf/nginx.conf
	    [ "$PHP_yn" == 'y' ] && [ -z "`grep '/php-fpm_status' $openresty_install_dir/nginx/conf/nginx.conf`" ] &&  sed -i "s@index index.html index.php;@index index.html index.php;\n    location ~ /php-fpm_status {\n        #fastcgi_pass remote_php_ip:9000;\n        fastcgi_pass unix:/dev/shm/php-cgi.sock;\n        fastcgi_index index.php;\n        include fastcgi.conf;\n        allow 127.0.0.1;\n        deny all;\n        }@" $openresty_install_dir/nginx/conf/nginx.conf
	fi
	
	mkdir $openresty_install_dir/nginx/conf/vhost

}